<template>
  <div>
      <div class="top_wrap">
        <div v-if="$route.query.CDid&&$route.query.status!='edit'" class="base_cover"></div>
        <div class="top_left">
            <el-form ref="ruleFormRef" :model="formData" :rules="ruleForm">
              <el-form-item label="课程名称：" prop="Cname">
                <el-input v-model="formData.Cname"></el-input>
              </el-form-item>
              <el-form-item label="课程描述：" prop="Cdes">
                <el-input v-model="formData.Cdes"></el-input>
              </el-form-item>
              <el-form-item label="课程价格：" prop="Cprice">
                <el-input v-model="formData.Cprice"></el-input>
              </el-form-item>
              <el-form-item label="课程分类：" class="cate">
                   <el-select v-model="CategoryOne">
            <el-option  :label="item.label" :value="item.value" v-for="item in optData.opt1" :key="item"></el-option>
          </el-select>
              <el-select v-model="CategoryTwo">
             <el-option  :label="item.label" :value="item.value" v-for="item in optData.opt2" :key="item"></el-option>
          </el-select>
          <el-select v-model="CategoryThree">
               <el-option  :label="item.label" :value="item.value" v-for="item in optData.opt3" :key="item"></el-option>
          </el-select>
              </el-form-item>
              <el-form-item>
                <el-button @click="onSumbmit(ruleFormRef)" type="success">保存</el-button>
              </el-form-item>
            </el-form>
        </div>
         <div class="top_right">
            <div class="img_info">
            <h1>课程封面</h1>
            <div class="course_img">
                <img :src="'http://localhost:3000'+Cpic">
                <div class="up_btn">
                    <el-link type="success">清除</el-link>
                    <el-link type="primary" @click="openflag">上传</el-link>
                </div>
            </div>
            </div>
         </div>
         <el-dialog  width="40%" v-model="upflag" title="上传课程封面">
            <el-upload
              class="upload-demo"
              action="/VueHandler/VueHandler/UpLoadPicHandler"
              :on-success="upsuccess"
              multiple
              method="post"
              :limit="3"
              :file-list="fileList"
            >
              <el-button type="primary">选择图片</el-button>
              <template #tip>
                <div class="el-upload__tip">
                  jpg/png files with a size less than 500kb
                </div>
              </template>
            </el-upload>
         </el-dialog>
      </div>
  </div>
</template>

<script lang="ts">
export default {

}
</script>
<script lang="ts" setup>
import { ref, reactive ,onBeforeMount,watch} from 'vue';
import { ElMessage, ElMessageBox ,ElForm} from 'element-plus'
import type { UploadFile } from 'element-plus/es/components/upload/src/upload.type'
import {addCourse,getCourseById,saveAllCourse} from '../../api/course'
import {useRouter,useRoute,onBeforeRouteUpdate} from 'vue-router'
import $bus from '../../utils/bus'
interface RawFile {
  name: string
  url: string
}
  let router=useRouter();
  let route=useRoute();
    type FormInstance = InstanceType<typeof ElForm>
        // 创建一个表单类型的数据
    const ruleFormRef = ref<FormInstance>()

    // 组件挂载前
    onBeforeMount(async ()=>{
        console.log(88888888)
        if(route.query.CDid){
          // 获取课程基本信息
          var res:any=await getCourseById(route.query.CDid);
          console.log(res)
          formData.Cname=res.data.courselist.Cname
          formData.Cdes=res.data.courselist.Cdescribe;
          formData.Cprice=res.data.courselist.Cprice;
          CategoryOne.value=res.data.courselist.CategoryOne;
          CategoryTwo.value=res.data.courselist.CategoryTwo;
           CategoryThree.value=res.data.courselist.CategoryThree;
           Cpic.value=res.data.courselist.Cpic;
        }
    })
    // 组件内部的路由拦截
  onBeforeRouteUpdate((to,from,next)=>{
    console.log(to)
    console.log(from)
    if(!to.query.CDid){ //如果去到当前组件 query中没有id
          formData.Cname=""
          formData.Cdes="";
          formData.Cprice="";
          CategoryOne.value="";
          CategoryTwo.value="";
           CategoryThree.value="";
           Cpic.value="";
          $bus.emit("cleardir")
    }
    next()
  })
  // 提交课程基本信息
  let onSumbmit=(elform:FormInstance)=>{
        if(!elform) return ;
        elform.validate(async (valid)=>{
            console.log(valid)
            if(valid&&Cpic.value){
                // 调用保存课程基本信息接口
                var res:any=await addCourse({
                      Cname: formData.Cname,		//课程名称	
                      Cdescribe: formData.Cdes,	//课程描述	
                      Cprice: formData.Cprice,		//价格	
                      CategoryOne: CategoryOne.value, //一级分类	
                      CategoryTwo: CategoryTwo.value,//		二级分类	
                      CategoryThree:CategoryThree.value,//		三级分类	
                      Cpic: Cpic.value, //封面图src地址
                })
                console.log(res);
                // ?c_id=622803cfdbce3e4ee8dbb6a4&CDid=55
                router.push({name:"addcourse",query:{c_id:res._id,CDid:res.ID}})
                ElMessage.success("课程添加成功")
            }else{
              // 表单验证失败
              ElMessage.error("表单信息不完整或封面未上传")
            }
        })
  }


let upflag=ref(false);
let Cpic=ref('');
// 上传成功的回调函数
let upsuccess=(res:any)=>{
    console.log("--------------------");
    console.log(res);
    Cpic.value=res.cacheName;
    upflag.value=false;
}
let openflag=()=>{
   upflag.value=true;
}

let CategoryOne=ref('');
let CategoryTwo=ref('');
let CategoryThree=ref('');
// 下拉框数据
let optData=reactive({
   opt1: [{
        value: "1",
        label: "前端"
        }, {
          value: "2",
          label: "后台"
        }, {
        value: "3",
        label: "视觉设计"
        }],
        opt2: [{
          value: "11",
          label: "JS"
        }, {
          value: "12",
          label: "Vue"
        }, {
        value: '13',
          label: "Webpack"
        },
        {
          value: "21",
          label: "Java"
        },
      {
        value: "22",
        label: "PHP"
      },
      {
        value: "22",
        label: "python"
      },
      {
        value: "31",
        label: "PS"
      },
      {
        value: "32",
        label: "蓝湖"
      },
      {
        value: "33",
        label: "Vi"
      }],
      opt3: [
        { value: "111", label: "js基础" },
        { value: "112", label: "js高级" }
      ]
})
// 表单需要v-model的数据
let formData=reactive({
    Cname:"",
    Cdes:"",
    Cprice:""
})  
// 接受父组件的事件 保存所有 编辑
   $bus.on("saveall",async ()=>{
     console.log("保存")
     console.log({
         Cname: formData.Cname,
        _id: route.query.c_id,   //课程_id
        Cdescribe: formData.Cdes,
        Cprice: formData.Cprice,
        CategoryOne:CategoryOne.value,
        CategoryTwo:CategoryTwo.value,
        CategoryThree: CategoryThree.value,
        Cpic: Cpic.value,
        Cdetails: ""
      })
      var res=await saveAllCourse({
         Cname: formData.Cname,
        _id: route.query.c_id,   //课程_id
        Cdescribe: formData.Cdes,
        Cprice: formData.Cprice,
        CategoryOne:CategoryOne.value,
        CategoryTwo:CategoryTwo.value,
        CategoryThree: CategoryThree.value,
        Cpic: Cpic.value,
        Cdetails: ""
      })
      console.log(res)
   })
let ruleForm={
    Cname:{required:true,message:"必填课程名称",trigger:"blur"},
    Cdes:{required:true,message:"必填课程描述",trigger:"blur"},
    Cprice:[
      {required:true,message:"必填课程描述",trigger:"blur"},
      {pattern:/^\d+$/,message:"至少一个数字",trigger:"blur" }
      ]
}
const fileList = ref<RawFile[]>([
  {
    name: 'food.jpeg',
    url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
  },
  {
    name: 'food2.jpeg',
    url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
  },
])

</script>
<style lang="less" scoped>
    .top_wrap{
      width: 100%;
      background: black;
      display: flex;
      position: relative;
      height: 350px;
      .base_cover{
        width: 100%;
       height: 350px;
       position: absolute;
       background: rgba(255,0,0,0.5);
       z-index: 88;
       top:0;
       left: 0;
      }
      .top_left{
        width: 60%;
         height: 350px;
         background: black;
         color: white;
        padding: 40px 50px ;
        box-sizing: border-box;
         .el-input{
           width: 300px;
         }
         .cate{
            .el-input{
                width: 100px;
                margin-right: 10px;
            }
         }
      }
      .top_right{
        width: 40%;
         height: 350px;
         background: black;
   
         .img_info{
            margin-left:50px;
           width: 300px;
           height: 300px;
           .up_btn{
             display: flex;
             justify-content: space-between;
           }
           img{
             width: 300px;
             height: 260px;
           }
         }
      }
    }
</style>